/*
 * Copyright (c) 2022.版权所有高金磊
 */

package 领扣算法.AA中等题.飞地的数量;

public class Main {
    public int numEnclaves(int[][] grid) {
        for (int i = 0; i < grid[0].length; i++) {
            if (grid[0][i]==1)
                grid[0][i]=2;
            if (grid[grid.length-1][i]==1)
                grid[grid.length-1][i]=2;
        }
        for (int i = 0; i < grid.length; i++) {
            if (grid[i][0]==1)
                grid[i][0]=2;
            if (grid[i][grid[0].length-1]==1)
                grid[i][grid[0].length-1]=2;
        }
        boolean marking=true;
        while (marking){
            marking=false;
            for (int i = 1; i < grid.length - 1; i++) {
                for (int j = 1; j <grid[0].length-1 ; j++) {
                    if (grid[i][j]==1){
                        if (grid[i-1][j]==2||grid[i][j-1]==2||grid[i+1][j]==2||grid[i][j+1]==2){
                            grid[i][j]=2;
                            marking=true;
                        }
                    }

                }
            }
        }
        int res=0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j]==1)
                    res++;
            }
        }
        return res;

    }
}
